package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.config.VodConstantProperties;
import com.atguigu.tingshu.album.mapper.AlbumInfoMapper;
import com.atguigu.tingshu.album.mapper.TrackInfoMapper;
import com.atguigu.tingshu.album.mapper.TrackStatMapper;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.RandomUtil;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.album.TrackStat;
import com.atguigu.tingshu.query.album.TrackInfoQuery;
import com.atguigu.tingshu.vo.album.TrackInfoVo;
import com.atguigu.tingshu.vo.album.TrackListVo;
import com.atguigu.tingshu.vo.album.TrackMediaInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class TrackInfoServiceImpl extends ServiceImpl<TrackInfoMapper, TrackInfo> implements TrackInfoService {

    @Autowired
    private TrackInfoMapper trackInfoMapper;

    @Autowired
    AlbumInfoMapper albumInfomapper;

    @Autowired
    VodService vodService;

    @Autowired
    TrackStatMapper trackStatMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveTrackInfo(TrackInfoVo trackInfoVo, Long userId) {
        //1.保存声音信息
        TrackInfo trackInfo = new TrackInfo();
        BeanUtils.copyProperties(trackInfoVo, trackInfo);
        trackInfo.setStatus(SystemConstant.TRACK_STATUS_PASS);
        trackInfo.setUserId(userId);

        AlbumInfo albumInfo = albumInfomapper.selectById(trackInfo.getAlbumId());

        //声音的序号
        trackInfo.setOrderNum(albumInfo.getIncludeTrackCount() + 1);
        //声音的相关数据集，可以调用API接口，mediaField查询
        TrackMediaInfoVo trackMediaInfoVo = vodService.getMediaInfo(trackInfo.getMediaFileId());
        trackInfo.setMediaDuration(trackMediaInfoVo.getDuration());
        trackInfo.setMediaUrl(trackMediaInfoVo.getMediaUrl());
        trackInfo.setMediaSize(trackMediaInfoVo.getSize());
        trackInfo.setMediaType(trackMediaInfoVo.getType());
        trackInfoMapper.insert(trackInfo);
        //2.保存统计信息
        this.saveTrackStat(trackInfo.getId(), SystemConstant.TRACK_STAT_PLAY);
        this.saveTrackStat(trackInfo.getId(), SystemConstant.TRACK_STAT_COLLECT);
        this.saveTrackStat(trackInfo.getId(), SystemConstant.TRACK_STAT_PRAISE);
        this.saveTrackStat(trackInfo.getId(), SystemConstant.TRACK_STAT_COMMENT);

        //3.保存声音和专辑关系
        albumInfo.setIncludeTrackCount(albumInfo.getIncludeTrackCount() + 1);
        albumInfomapper.updateById(albumInfo);
    }

    public void saveTrackStat(Long trackId, String statType) {
        TrackStat trackStat = new TrackStat();
        trackStat.setTrackId(trackId);
        trackStat.setStatType(statType);
        trackStat.setStatNum(new Random().nextInt(100000));
        trackStatMapper.insert(trackStat);
    }

    @Override
    public IPage<TrackListVo> findUserTrackPage(Page<TrackInfoVo> trackInfoVoPage, TrackInfoQuery trackInfoQuery) {
        return trackInfoMapper.selectTrackPage(trackInfoVoPage, trackInfoQuery);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeTrackInfo(Long id) {
        try {
            //获取声音对象
            TrackInfo trackInfo = trackInfoMapper.selectById(id);
            //删除声音
            this.removeById(id);

            //维护序号问题
            trackInfoMapper.updateOrderNum(trackInfo.getAlbumId(), trackInfo.getOrderNum());

            //删除统计数据
            trackStatMapper.delete(new LambdaQueryWrapper<TrackStat>().eq(TrackStat::getTrackId, id));
            //维护专辑数量问题
            AlbumInfo albumInfo = albumInfomapper.selectOne(new LambdaQueryWrapper<AlbumInfo>().eq(AlbumInfo::getId, trackInfo.getAlbumId()));
            albumInfo.setIncludeTrackCount(albumInfo.getIncludeTrackCount() - 1);
            albumInfomapper.updateById(albumInfo);

            //删除云点播的声音
            vodService.deleteMedia(trackInfo.getMediaFileId());
			//删除成功
            return true;
        } catch (Exception e) {
            //删除失败，记录日志信息
            log.error(e.getMessage(), e);
        }
		//删除失败
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTrackInfo(Long trackId, TrackInfoVo trackInfoVo) {
        //获取声音对象
        TrackInfo trackInfo = this.getById(trackId);

        //获取传递的fileId
        String mediaFileId = trackInfo.getMediaFileId();
        BeanUtils.copyProperties(trackInfoVo, trackInfo);

        //获取页面的声音信息，和数据库中的声音信息进行对比
        if (!trackInfoVo.getMediaFileId().equals(mediaFileId)) {
            //说明已经修改了
            TrackMediaInfoVo mediaInfo = vodService.getMediaInfo(trackInfoVo.getMediaFileId());

            if (null == mediaInfo){
                throw new GuiguException(ResultCodeEnum.VOD_FILE_ID_ERROR);
            }
            //对新的流媒体属性赋值
            trackInfo.setMediaDuration(mediaInfo.getDuration());
            trackInfo.setMediaUrl(mediaInfo.getMediaUrl());
            trackInfo.setMediaSize(mediaInfo.getSize());
            trackInfo.setMediaType(mediaInfo.getType());
            //原来的不需要了
            vodService.deleteMedia(mediaFileId);
        }
        //更新数据
        trackInfoMapper.updateById(trackInfo);
    }
}
